<script setup lang="ts">
import { onMounted, ref, reactive, computed } from 'vue'
import LineHeader from '@/components/LineHeader.vue'
import {
  createOrder,
  deleteOrderById,
  deleteOrderByIdList,
  getOrderById,
  getOrderList,
  updateOrder,
} from '@/apis/order'
import {
  ElMessage,
  type FormInstance,
  type FormRules,
  ElMessageBox,
  type Action,
} from 'element-plus'

/**
 * 订单数量
 */
const defaultSelect = ref(1)
const allOrdersCount = ref(0)
const confirmedOrdersCount = ref(0)
const notConfirmedOrdersCount = ref(0)
const canceledOrdersCount = ref(0)

/**
 * 检索的订单类型
 */
const selectOrdersType = async (value: number) => {
  defaultSelect.value = value
  if (value === 1) {
    orderStatus.value = ''
  } else if (value === 2) {
    orderStatus.value = '已确认'
  } else if (value === 3) {
    orderStatus.value = '待确认'
  } else if (value === 4) {
    orderStatus.value = '已取消'
  }
  await initOrders()
}
const orderStatus = ref('')

/**
 * 订单列表
 */
const orderList = ref()

import type { ComponentSize } from 'element-plus'
const currentPage = ref(1)
const pageSize = ref(10)
const totalSize = ref(0)
const size = ref<ComponentSize>('default')
const background = ref(false)
const disabled = ref(false)

const handleSizeChange = async (val: number) => {
  console.log(`${val} items per page`)
  await initOrders()
}
const handleCurrentChange = async (val: number) => {
  console.log(`current page: ${val}`)
  await initOrders()
}

const skuInput = ref('')
const orderIdInput = ref('')

/**
 * 添加订单
 */
// 添加订单弹窗
const addOrderFormVisible = ref(false)
// 添加订单表单
const addOrderForm: any = ref({
  SKU: '',
  Amount: '',
  Remarks: '',
})
// 添加表单对象
const addOrderFormRef = ref()
// 打开添加订单弹窗
const openAddOrderForm = () => {
  addOrderFormVisible.value = true
}
// 添加表单校验规则
const addOrderFormRules = reactive<FormRules>({
  SKU: [
    {
      required: true,
      message: '请输入商品SKU',
      trigger: 'blur',
    },
  ],
  Amount: [
    {
      required: true,
      message: '请输入商品数量',
      trigger: 'blur',
    },
  ],
  Remarks: [
    {
      required: true,
      message: '请输入订单备注',
      trigger: 'blur',
    },
  ],
})

// 添加订单表单提交
const submitAddOrdersForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      console.log('添加订单')
      const res = await createOrder(addOrderForm.value)
      if (res.data.error == null) {
        ElMessage({
          message: '添加成功',
          type: 'success',
        })
        addOrderFormVisible.value = false
        console.log(res)
      } else {
        ElMessage({
          message: '添加失败 ' + res.data.error,
          type: 'error',
        })
      }
    } else {
      console.log('error submit!', fields)
    }
  })
}

/**
 * 编辑订单
 */
// 打开编辑订单弹窗
const handleEdit = async (index: number, row: any) => {
  const res = await getOrderById(row.OrderID)
  editOrderForm.value = res.data
  editOrderFormVisible.value = true
  editOrderForm.value.ID = row.OrderID
  console.log(editOrderForm.value)
}

// 编辑订单弹窗
const editOrderFormVisible = ref(false)
// 编辑订单表单
const editOrderForm: any = ref({
  OrderID: 0,
  Status: '',
  CreatedAt: '',
  UpdatedAt: '',
  SKU: '',
  Amount: 0,
  Remarks: '',
})
// 编辑表单对象
const editOrderFormRef = ref()

// 编辑订单表单提交
const submitEditOrdersForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      console.log('编辑订单')
      const res = await updateOrder(editOrderForm.value.ID, editOrderForm.value)
      if (res.status === 200) {
        ElMessage({
          message: '编辑成功',
          type: 'success',
        })
        editOrderFormVisible.value = false
        console.log(res)
      } else {
        ElMessage({
          message: '编辑失败',
          type: 'error',
        })
      }
    } else {
      console.log('error submit!', fields)
    }
  })
}

// 订单状态
const statusOptions = [
  {
    label: '确认',
    value: 'confirm',
  },
  {
    label: '取消',
    value: 'cancel',
  },
]

/**
 * 删除订单
 */
// 删除订单
const handleDelete = (index: number, row: any) => {
  console.log(index, row)
  ElMessageBox.alert('确认删除 ' + row.OrderID + ' 订单？', '删除订单', {
    confirmButtonText: '确认',
    callback: async (action: Action) => {
      if (action === 'confirm') {
        ElMessage({
          type: 'success',
          message: `删除${row.OrderID}订单成功`,
        })
        await deleteOrderById(row.OrderID)

        // 删除 ordersList 中的数据
        orderList.value.splice(index, 1)
      } else {
        ElMessage({
          type: 'error',
          message: `删除${row.Name}订单失败`,
        })
      }
    },
  })
}
/**
 * 批量删除
 */
/**
 * 获取要删除的列表
 */
type Order = {
  OrderID: 0
}
const selectable = (row: Order) => ![-100].includes(row.OrderID)
const deleteButtonDisable = computed(() => {
  if (deleteOrderList.value.length === 0) {
    return true
  } else {
    return false
  }
})
const deleteOrderList: any = ref([])
const deleteOrderIdList: any = ref()
const handleSelectionChange = (val: any) => {
  deleteOrderList.value = val
  deleteOrderIdList.value = val.map((item: any) => item.OrderID)
  console.log(deleteOrderIdList.value)
}
const handleBatchDelete = () => {
  ElMessageBox.alert('确认删除已选订单？', '删除订单', {
    confirmButtonText: '确认',
    callback: async (action: Action) => {
      if (action === 'confirm') {
        ElMessage({
          type: 'success',
          message: `删除订单成功`,
        })
        await deleteOrderByIdList(deleteOrderIdList.value)

        window.location.reload()
      } else {
        ElMessage({
          type: 'error',
          message: `删除订单失败`,
        })
      }
    },
  })
}
// 获取数据
const initOrders = async () => {
  const orders = await getOrderList({
    page: currentPage.value,
    size: pageSize.value,
    status: orderStatus.value,
    sku: skuInput.value,
    orderid: orderIdInput.value,
  })

  orderList.value = orders.data
  totalSize.value = orders.totalSize.all

  allOrdersCount.value = orders.totalSize.all
  confirmedOrdersCount.value = orders.totalSize.confirmed
  notConfirmedOrdersCount.value = orders.totalSize.not_confirm
  canceledOrdersCount.value = orders.totalSize.canceled
}

// 初始化
onMounted(async () => {
  await initOrders()
  console.log(orderList.value)
})
</script>
<template>
  <div id="orders">
    <el-container style="height: 100%">
      <el-main>
        <LineHeader #text>订单列表</LineHeader>

        <!-- 头部 -->
        <el-row class="options-row">
          <el-col :span="8">
            <div class="options">
              <el-button
                :class="{ 'el-button--primary': defaultSelect === 1 }"
                @click="selectOrdersType(1)"
                >全部订单({{ allOrdersCount }})</el-button
              >
              <el-button
                :class="{ 'el-button--primary': defaultSelect === 2 }"
                @click="selectOrdersType(2)"
                >已确认({{ confirmedOrdersCount }})</el-button
              >
              <el-button
                :class="{ 'el-button--primary': defaultSelect === 3 }"
                @click="selectOrdersType(3)"
                >待确认({{ notConfirmedOrdersCount }})</el-button
              >
              <el-button
                :class="{ 'el-button--primary': defaultSelect === 4 }"
                @click="selectOrdersType(4)"
                >已取消({{ canceledOrdersCount }})</el-button
              >
            </div></el-col
          >
          <el-col :span="8">
            <div class="search">
              <p>订单搜索：</p>
              <el-input v-model="skuInput" style="width: 200px" placeholder="SKU号码" />
              <el-input v-model="orderIdInput" style="width: 200px" placeholder="订单ID" />
              <el-button class="search-button" type="primary" @click="initOrders">搜索</el-button>
            </div></el-col
          >
          <el-col :span="8">
            <div class="add">
              <el-button class="add-button" type="primary" @click="openAddOrderForm"
                >添加订单</el-button
              >
              <el-button
                class="delete-button"
                type="danger"
                @click="handleBatchDelete"
                :disabled="deleteButtonDisable"
                >批量删除</el-button
              >
            </div>
          </el-col>
        </el-row>

        <!-- 订单数据 -->
        <el-table
          ref="multipleTableRef"
          :data="orderList"
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" :selectable="selectable" width="55" />
          <el-table-column label="订单ID">
            <template #default="scope">{{ scope.row.OrderID }}</template>
          </el-table-column>
          <el-table-column property="Status" label="状态" />
          <el-table-column property="CreatedAt" label="创建订单时间" />
          <el-table-column property="UpdatedAt" label="更新订单时间" />
          <el-table-column property="SKU" label="SKU ID" />
          <el-table-column property="Amount" label="数量" />
          <el-table-column property="Remarks" label="备注" />
          <el-table-column label="操作">
            <template #default="scope">
              <el-button type="primary" @click="handleEdit(scope.$index, scope.row)">
                编辑
              </el-button>
              <el-button type="danger" @click="handleDelete(scope.$index, scope.row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="page">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 30, 50]"
            :size="size"
            :disabled="disabled"
            :background="background"
            layout="total, sizes, prev, pager, next"
            :total="totalSize"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-main>
    </el-container>

    <!-- 添加订单 -->
    <el-dialog v-model="addOrderFormVisible" title="添加订单" width="800">
      <el-form :model="addOrderForm" ref="addOrderFormRef" :rules="addOrderFormRules">
        <el-form-item label="SKU ID" prop="SKU">
          <el-input v-model="addOrderForm.SKU" autocomplete="off" />
        </el-form-item>
        <el-form-item label="商品数量" prop="Amount">
          <el-input v-model="addOrderForm.Amount" autocomplete="off" />
        </el-form-item>
        <el-form-item label="订单备注" prop="Remarks">
          <el-input v-model="addOrderForm.Remarks" autocomplete="off" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="addOrderFormVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAddOrdersForm(addOrderFormRef)"> 添加 </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 编辑订单 -->
    <el-dialog v-model="editOrderFormVisible" title="编辑订单" width="800">
      <el-form :model="editOrderForm" ref="editOrderFormRef">
        <el-form-item label="订单ID" label-width="100px">
          <el-input v-model="editOrderForm.OrderID" autocomplete="off" disabled />
        </el-form-item>
        <el-form-item label="订单状态" label-width="100px">
          <el-select v-model="editOrderForm.Status" placeholder="请选择订单状态">
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="创建订单时间" label-width="100px">
          <el-input v-model="editOrderForm.CreatedAt" autocomplete="off" disabled />
        </el-form-item>
        <el-form-item label="更新订单时间" label-width="100px">
          <el-input v-model="editOrderForm.UpdatedAt" autocomplete="off" disabled />
        </el-form-item>
        <el-form-item label="SKU ID" label-width="100px">
          <el-input v-model="editOrderForm.SKU" autocomplete="off" disabled />
        </el-form-item>
        <el-form-item label="商品数量" label-width="100px">
          <el-input v-model="editOrderForm.Amount" autocomplete="off" disabled />
        </el-form-item>
        <el-form-item label="订单备注" label-width="100px">
          <el-input v-model="editOrderForm.Remarks" autocomplete="off" disabled />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editOrderFormVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEditOrdersForm(editOrderFormRef)">
            编辑
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<style scoped lang="scss">
#orders {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 16px 32px;
  box-sizing: border-box;

  .options-row {
    margin-bottom: 16px;
  }

  .options,
  .search,
  .add {
    width: 100%;
    height: 64px;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .search {
    .search-button {
      padding: 0 32px;
      margin-left: 16px;
    }
  }

  .add {
    .add-button {
      padding: 0 48px;
    }
  }

  .page {
    width: 100%;
    display: flex;
    justify-content: center;
    margin-top: 32px;
  }
}
</style>
